package com.sudo.boot.admin._wx;

import cn.dev33.satoken.annotation.SaIgnore;
import com.boot.starter.redis.component.RedisKeys;
import com.sudo.boot.base.pojo.JsonRes;
import com.sudo.boot.satoken.util.BootStpUtil;
import com.sudo.boot.satoken.util.SaRedisUtil;
import com.sudo.boot.service.wx.WxUserService;
import com.sudo.boot.weixin.serivce.Oauth2Service;
import com.sudo.boot.weixin.util.WxUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/wx-user")
@RequiredArgsConstructor
public class WxUserController {

    private final WxUserService wxUserService;
    private final Oauth2Service oauth2Service;
    private final SaRedisUtil saRedisUtil;


    @SaIgnore
    @RequestMapping("check")
    public String wxCheck(@RequestParam("signature") String signature,
                          @RequestParam("timestamp") String timestamp,
                          @RequestParam("nonce") String nonce,
                          @RequestParam(value = "echostr", required = false) String echostr) {
        oauth2Service.wxCheck(signature, timestamp, nonce, echostr);
        return echostr;
    }

    @GetMapping("/bind/qrcode")
    public JsonRes<String> qrCode() {
        String state = WxUtil.BIND + BootStpUtil.getCurrUserId();
        // 设置二维码的过期时间为5分钟
        String qrCodeBind = RedisKeys.qrCodeOverdue(state);
        saRedisUtil.set(qrCodeBind, 1, 300);
        String qrCodeUrl = oauth2Service.createQrCodeUrl(state);
        log.info("生成微信授权二维码：{}", qrCodeUrl);
        return JsonRes.ok(qrCodeUrl);
    }

    @PostMapping("/bind/unbindWx")
    public JsonRes<Void> unbindWx() {
        Long currUserId = Long.valueOf(BootStpUtil.getCurrUserId());
        wxUserService.unbindWx(currUserId);
        return JsonRes.ok();
    }

    @GetMapping("/bind/wxStatus")
    public JsonRes<Boolean> bindWxStatus() {
        Long currUserId = Long.valueOf(BootStpUtil.getCurrUserId());
        boolean bindWxStatus = wxUserService.bindWxStatus(currUserId);
        return JsonRes.ok(bindWxStatus);
    }
}
